package com.wsz.security_fx.controller;

import com.alibaba.fastjson.JSON;
import com.auth0.jwt.interfaces.DecodedJWT;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.wsz.security_fx.utils.JwtUtils;
import com.wsz.security_fx.pojo.Role;
import com.wsz.security_fx.pojo.User;
import com.wsz.security_fx.pojo.UserRole;
import com.wsz.security_fx.service.UserRoleService;
import com.wsz.security_fx.service.UserService;
import lombok.RequiredArgsConstructor;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import static org.springframework.http.HttpHeaders.AUTHORIZATION;

@RequiredArgsConstructor
@RestController
@RequestMapping("/api")
public class TestController {

    private final UserService userService;
    private final UserRoleService userRoleService;

    @GetMapping("/user/users")
    public ResponseEntity<List<User>> test(){
        return ResponseEntity.ok().body(userService.list());
    }

    @PostMapping("/user/save")
    public void saveUser(@RequestBody User user){
        userService.save(user);
    }

    @DeleteMapping("/user/delete/{id}")
    public void deleteUser(@PathVariable int id){
        userService.removeById(id);
    }

    @PostMapping("/user/update")
    public void updateUser(@RequestBody User user){
        userService.updateById(user);
    }

    @PostMapping("/user/user_role/save")
    public void saveUserRole(@RequestBody UserRole userRole){
        userRoleService.save(userRole);
    }

    @PostMapping("/token/refresh")
    public void refreshToken(HttpServletRequest request, HttpServletResponse response) throws IOException {
        String header = request.getHeader(AUTHORIZATION);
        System.out.println(header);
        if(header != null && header.startsWith("token ")){
            try{
                System.out.println();

                String refresh_token = header.substring("token ".length());
                System.out.println(refresh_token);
                DecodedJWT decodedJWT = JwtUtils.parseToken(refresh_token);

                String username = decodedJWT.getSubject();
                System.out.println(username);

                User user = userService.getUserByUserName(username);

                String access_token = JwtUtils.createAccessToken(username,request.getRequestURI(),user.getRoles().stream().map(Role::getName).collect(Collectors.toList()));

                Map<String,String> tokens = new HashMap<>();
                tokens.put("access_token",access_token);
                tokens.put("refresh_token",refresh_token);
                response.setContentType("application/json;UTF-8");
                new ObjectMapper().writeValue(response.getOutputStream(),tokens);

            }catch (Exception e){
                response.setHeader("error",e.getMessage());
                response.setStatus(403);
                Map<String,String> error = new HashMap<>();
                error.put("error_msg",e.getMessage());
                response.setContentType("application/json;UTF-8");
                new ObjectMapper().writeValue(response.getOutputStream(),error);
            }
        }else{
            throw new RuntimeException("刷新令牌丢失");
        }
    }

}
